package tongcheng.com.tongcheng.ui.yemian.mapui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.IdRes;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import tongcheng.com.tongcheng.ConStans;
import tongcheng.com.tongcheng.R;
import tongcheng.com.tongcheng.base.AllOrderDetialActivity;
import tongcheng.com.tongcheng.base.BaseActivity;
import tongcheng.com.tongcheng.base.main.activity.LiuYanFanKuiActivity;
import tongcheng.com.tongcheng.base.main.dailishangcenter.DPersonCenterActivity;
import tongcheng.com.tongcheng.bean.MapDataBean;
import tongcheng.com.tongcheng.network.CallServer;
import tongcheng.com.tongcheng.network.MyRequest;
import tongcheng.com.tongcheng.network.OnCallBack;
import tongcheng.com.tongcheng.utils.GsonUtil;
import tongcheng.com.tongcheng.utils.Setting;
import tongcheng.com.tongcheng.utils.ShowToast;
import tongcheng.com.tongcheng.widght.MapTopPopWindow;

public class DaiLiQiangDanActivity extends BaseActivity implements LocationSource, AMapLocationListener {

    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.title)
    TextView mTitle;
    @Bind(R.id.kefu)
    ImageView mKefu;
    @Bind(R.id.title_bar)
    RelativeLayout mBg;
    @Bind(R.id.dailishang_dingwei)
    ImageView mDailishangDingwei;
    @Bind(R.id.dailishang_dingdan)
    ImageView mDailishangQiangdan;
    @Bind(R.id.dailishang_ditu)
    MapView mDailishangDitu;
    @Bind(R.id.dailishang_rb1)
    RadioButton mDailishangRb1;
    @Bind(R.id.dailishang_rb2)
    RadioButton mDailishangRb2;
    @Bind(R.id.dailishang_rb3)
    RadioButton mDailishangRb3;
    @Bind(R.id.dailishang_rg)
    RadioGroup mDailishangRg;
    private AMap aMap;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private OnLocationChangedListener mListener;

    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private ArrayList<MarkerOptions> optionsList = new ArrayList<>();



    @Override
    public Integer initResid() {
        return R.layout.activity_dai_li_qiang_dan;
    }

    @Override
    public void initCreate(Bundle savedInstanceState) {
        mDailishangRb1.setChecked(true);
//        hideBottomUIMenu();
        initquaqnxian();
        settitlebar(mBg);
        mDailishangDitu.onCreate(savedInstanceState);

        initMap();
        initLoc();

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startactivity(DaiLiQiangDanActivity.this, DPersonCenterActivity.class);
            }
        });

        mKefu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startactivity(DaiLiQiangDanActivity.this,LiuYanFanKuiActivity.class);
            }
        });

        mDailishangDingwei.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 集成地图以后刷新定位
                //initLoc();


                ReDingwei();
                //  Toast.makeText(DaiLiQiangDanActivity.this,"我被点了",Toast.LENGTH_SHORT).show();
            }
        });
        mDailishangQiangdan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent nIntent = new Intent(DaiLiQiangDanActivity.this, DPersonCenterActivity.class);
//                nIntent.putExtra("bool",true);
//                startActivity(nIntent);

                Setting.setTemp(1);
                startactivity(DaiLiQiangDanActivity.this, DPersonCenterActivity.class);
            }
        });

        mDailishangRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                if (i == R.id.dailishang_rb1) {
                    DrawPointInMap(2);
                } else if (i == R.id.dailishang_rb2) {
                    DrawPointInMap(0);
                } else if (i == R.id.dailishang_rb3) {
                    DrawPointInMap(1);
                }
            }
        });

        mDailishangDitu.onCreate(this.savedInstanceState);
    }

    private void initMap() {
        //获取地图对象
        aMap = mDailishangDitu.getMap();
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                marker.setIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(),
                                R.mipmap.bashou_big)));
                MapTopPopWindow MapTopPopWindow = new MapTopPopWindow(DaiLiQiangDanActivity.this, DaiLiQiangDanActivity.this, marker);
                MapTopPopWindow.show(mBg);
                MapTopPopWindow.setOnItemClickLitener(new MapTopPopWindow.OnBackLitener() {
                    @Override
                    public void onBackClick(MapDataBean.DataBean item) {
                        Intent intent = new Intent(DaiLiQiangDanActivity.this, AllOrderDetialActivity.class);
                        intent.putExtra("order_type", item.order_type);
                        intent.putExtra("status", item.status);
                        intent.putExtra("id", item.id);
                        startActivity(intent);
                    }
                });
                return true;
            }
        });


        //设置显示定位按钮 并且可以点击
        UiSettings settings = aMap.getUiSettings();
        //设置定位监听
        aMap.setLocationSource(this);
        // 是否显示定位按钮
        settings.setMyLocationButtonEnabled(false);
        // 是否可触发定位并显示定位层
        aMap.setMyLocationEnabled(true);
        //不显示缩放按钮
        settings.setZoomControlsEnabled(false);
        //隐藏高德地图logo
        settings.setLogoBottomMargin(-50);//隐藏logo
        //定位的小图标 默认是蓝点 这里自定义一团火，其实就是一张图片
       /* MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher));
        myLocationStyle.radiusFillColor(android.R.color.transparent);
        myLocationStyle.strokeColor(android.R.color.transparent);
        aMap.setMyLocationStyle(myLocationStyle);*/


        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        //蓝点圆圈颜色
        myLocationStyle.strokeColor(Color.TRANSPARENT);
        //圆圈填充颜色
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.fangxiang));
        myLocationStyle.radiusFillColor(0x6200f2ff);
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
//aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

// 绑定 Marker 被点击事件
    }


    //重新定位
    private void ReDingwei() {

        //设置缩放级别
        // aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
        //将地图移动到定位点\
        if (aMapLocation != null) {
            mListener.onLocationChanged(aMapLocation);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
        } else {
            ShowToast.showToast("当前信号弱,定位失败");
        }

        //添加图钉
        //aMap.addMarker(getMarkerOptions(aMapLocation));
    }

    private void initquaqnxian() {
        AndPermission.with(this)
                .requestCode(200)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_WIFI_STATE
                        , Manifest.permission.ACCESS_NETWORK_STATE
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE
                        //      , Manifest.permission.WAKE_LOCK

                        // ,Manifest.permission.WRITE_SETTINGS
                )
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(DaiLiQiangDanActivity.this, rationale).show();

                    }
                })
                .callback(listener)
                .start();
    }

    private void DrawPointInMap(final int type) {

        MyRequest request = new MyRequest(ConStans.DrwaPointInMap_Url, RequestMethod.GET);
        request.add("userid", Setting.getId());
        request.add("type", type);
        CallServer.getInstance().addPost(this,request, 1, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                MapDataBean mapDataBean = GsonUtil.GsonToBean(json, MapDataBean.class);
                if (mapDataBean != null) {
                    if (type == 2) {
                        mDailishangRb1.setChecked(true);
                    }
                    ReDingwei();
                    optionsList.clear();
                    //aMap.getMapScreenMarkers().clear();
                    clearMarkers();
                    List<MapDataBean.DataBean> datas = mapDataBean.data;

                    if (datas != null) {
                        for (int i = 0; i < datas.size(); i++) {
                            MapDataBean.DataBean dataBean = datas.get(i);
                            String lng = dataBean.lng;
                            String lat = dataBean.lat;
                            double jindu = Double.parseDouble(lng);
                            double weidu = Double.parseDouble(lat);
                            MarkerOptions markerOptions = getMarkerOptions(weidu, jindu);
                            optionsList.add(markerOptions);
                        }
                    }


                    ArrayList<Marker> markers = aMap.addMarkers(optionsList, true);
                    if (markers != null) {
                        for (int i = 0; i < markers.size(); i++) {
                            Marker marker = markers.get(i);
                            marker.setObject(datas.get(i));
                        }
                    }

                }


            }
        });
    }

    //删除指定Marker
    private void clearMarkers() {
        //获取地图上所有Marker
        List<Marker> mapScreenMarkers = aMap.getMapScreenMarkers();
        for (int i = 0; i < mapScreenMarkers.size(); i++) {
            Marker marker = mapScreenMarkers.get(i);
            if (marker.getObject() instanceof MapDataBean.DataBean) {
                marker.remove();//移除当前Marker
            }
        }

    }

    //定位
    private void initLoc() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;

    }

    @Override
    public void deactivate() {
        mListener = null;
    }

    public AMapLocation aMapLocation;

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            this.aMapLocation = aMapLocation;
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
                Setting.setJinDu( aMapLocation.getLongitude());
                Setting.setWeiDu(aMapLocation.getLatitude());
                aMapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码

                // 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
                if (isFirstLoc) {
                    //设置缩放级别
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
                    //将地图移动到定位点

                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude())));
                    //点击定位按钮 能够将地图的中心移动到定位点
                    mListener.onLocationChanged(aMapLocation);
                    //添加图钉
                 /*   Marker marker = aMap.addMarker(getMarkerOptions(aMapLocation));
                    marker.setClickable(true);
                    //获取定位信息
                    StringBuffer buffer = new StringBuffer();
                    buffer.append(aMapLocation.getCountry() + "" + aMapLocation.getProvince() + "" + aMapLocation.getCity() + "" + aMapLocation.getProvince() + "" + aMapLocation.getDistrict() + "" + aMapLocation.getStreet() + "" + aMapLocation.getStreetNum());
                    Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();*/
                    isFirstLoc = false;
                }


            } else {
              /*  //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());

                Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();*/
            }
        }


    }

    //自定义一个图钉，并且设置图标，当我们点击图钉时，显示设置的信息
    private MarkerOptions getMarkerOptions(double jindu, double weidu) {
        //设置图钉选项
        MarkerOptions options = new MarkerOptions();
        options.setFlat(true);
        //图标

        options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),
                        R.mipmap.bashou)));
        //位置
        options.position(new LatLng(weidu, jindu));


        return options;

    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mDailishangDitu.onResume();
        //画全部的点
        DrawPointInMap(2);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mDailishangDitu.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mDailishangDitu.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDailishangDitu.onDestroy();
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。

            // 这里的requestCode就是申请时设置的requestCode。
            // 和onActivityResult()的requestCode一样，用来区分多个不同的请求。
            if (requestCode == 200) {
              /*  if (TextUtils.isEmpty(SPUtil.getString(StartActivity.this,"keysss"))) {
                    Ioc.getIoc().init(MyApplication.app);
                } else {
                    SPUtil.put(StartActivity.this,"keysss",123);
                }*/

                Log.e("sld", "成功1");
                //myHandler.sendEmptyMessageDelayed(1, 3000);


                // TODO ...
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == 200) {
                // 显示缺失权限提示
                showMissingPermissionDialog();
                Log.e("sld", "shibai");
                Log.e("sld", deniedPermissions.size() + "");
            }
        }
    };


    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("帮助");
        builder.setMessage("当前应用缺少必要权限\n请点击-设置-权限-打开所需权限.");

        // 拒绝, 退出应用
        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setResult(1);
                finish();
            }
        });

        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.show();
    }


    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
